const  {logI,logE}  = require('../../log.js')
const admin = require('firebase-admin');
const credentials = require('../cameraproject-firebase-adminsdk.json');
const app = admin.initializeApp({
    credential: admin.credential.cert(credentials)
});
const domain = process.env.DOMAIN
exports.sendFCM = async (tokens, fbMsg) => {
    const body = fbMsg.nickname == ""?"登録外の人物を検知しました": fbMsg.nickname+"が帰ってきました";
    const message = {
        tokens: tokens,
        notification: {
            title: 'OD CAMERA',
            body: body,
            imageUrl: "https://"+domain+fbMsg.imgUrl
        }
    };
    logI('odelic server -> fcm server', fbMsg.mac,'sendFCM', `sendFCM message: ${JSON.stringify(message)}`);
    await app.messaging().sendEachForMulticast(message,false)
        .then((response)=> {
        logI('fcm server -> odelic server', fbMsg.mac,'sendFCM', `sendFCM response: ${JSON.stringify(response)},sendFCM message: ${JSON.stringify(message)}`);
        let tokensToRemove = [];
        response.responses.forEach((result, index) => {
            const error = result.error;
            if (error) {
                // Cleanup the tokens who are not registered anymore.
                if (error.code === 'messaging/invalid-registration-token' ||
                    error.code === 'messaging/registration-token-not-registered') {
                    tokensToRemove.push(tokens[index]);
                }
            }
        });
        console.log(tokensToRemove);
    })
    .catch((error) => {
        logE('fcm server -> odelic server', fbMsg.mac,'sendFCM', `sendFCM error: ${error}`);
    });
    /*try {
        const response = await app.messaging().sendEachForMulticast(message,false);
        logI('fcm server -> odelic server', fbMsg.mac,'sendFCM', `sendFCM response: ${JSON.stringify(response)},sendFCM message: ${JSON.stringify(message)}`);
    } catch (error) {
        logE('fcm server -> odelic server', 'sendFCM', `sendFCM error: ${error}`);
    }*/
}

